package com.heima.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;

import com.heima.utils.common.AppJwtUtil;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;


import java.util.List;
import java.util.Map;


@Service
@Transactional
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser>
        implements AdUserService {

    /**
     * 登录
     *
     *
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        //1.参数校验,如果用户名跟密码为空
        if(StringUtils.isBlank(adUserDto.getName()) || StringUtils.isBlank(adUserDto.getPassword()) ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名跟密码不能为空");
        }

        //如果传递参数中用户名跟密码不为空,跟数据库中用户名,密码匹配
        LambdaQueryWrapper<AdUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdUser::getName,adUserDto.getName());
        List<AdUser> list = list(lambdaQueryWrapper);

        if(list != null ||list.size() == 1){
            //查询出用户信息操作
            //获取查询出来的用户信息(密码的密文,盐)
            AdUser adUser = list.get(0);
            //查询出用户,匹配密码
            //拿着页面输入的密码+ 盐 进行MD5加密
             String pswd = DigestUtils.md5DigestAsHex((adUserDto.getPassword() +adUser.getSalt()).getBytes());

             //之后与数据库中查询出来的密码密文进行匹配
            if(adUser.getPassword().equals(pswd)){
                //密码一致
              Map<String,Object> map = Maps.newHashMap();

              adUser.setPassword("");
              adUser.setSalt("");
              //登录成功,生成token
              map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                //登陆成功之后，将生成的token和用户的基本信息（不包含密码和盐)交给页面存储
                map.put("user",adUser);
                return ResponseResult.okResult(map);
            }else{
                //密码不一致
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
        }else{
            //查询不出来用户信息
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }

    }
}
